const { Notification } = require("electron");
const path = require("node:path");
const {
	getData: getModuleData,
	saveData: saveModuleData,
} = require("./storage");

//本线程永久循环任务
let intervalTask = undefined;

module.exports = () => {
	//延迟5s检测和提示，以提高性能
	intervalTask = setInterval(async () => {
		//每秒执行任务完成检测
		const tasks = await getTasks();
		const nowMils = new Date().getTime();
		tasks.forEach((group) => {
			const finishedList = group.list.filter(
				(e) => e.createdMils + e.waitMils - nowMils <= 0
			);
			finishedList.forEach(async (item) => {
				//进行提示
				if (!item.finished) {
					sendNotification(item, group.labelName);
					await finishTask(item.id);
				}
			});
		});
	}, 5000);
};

//获取任务列表
const getTasks = async () => {
	const data = await getModuleData("coc");
	return data.tasks;
};

//设置任务通知完成
const finishTask = async (itemId) => {
	const tasks = await getTasks();
	const resTasks = [];
	for (const group of tasks) {
		const list = group.list;
		const aim = list.find((e) => e.id === itemId);
		if (!aim) {
			resTasks.push(group);
		} else {
			group.list = [
				...list.filter((e) => e.id !== itemId),
				{ ...aim, finished: 1 },
			];
			resTasks.push(group);
		}
	}
	await saveModuleData({ tasks: resTasks }, "coc");
};

//发送系统通知
const sendNotification = (item, groupName) => {
	new Notification({
		title: "批量计时任务完成",
		body: `[${groupName}] ${item.note}`,
		urgency: "critical",
		timeoutType: "never",
		icon: path.join(__dirname, "../assets/PlantB.ico"),
	}).show();
};
